package com.senior.locksuppor;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

public class LockSupportDemo {

    static Object object = new Object();
    static Lock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();

    public static void main(String[] args) {
        //正常流程是先阻塞，然后别通知你启动
        //这个只要发了通知，后面阻塞的也可以醒过来
        Thread t1 = new Thread(()->{
            //这个不需要锁，也可以
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } //下面可以先发出通知，也就是说，不用遵守顺序
            System.out.println(Thread.currentThread().getName()+"Come in...,开始等待");
            LockSupport.park();
            System.out.println(Thread.currentThread().getName()+"被叫醒了，等待结束");
        },"T1");
        t1.start();

        new Thread(()->{
            System.out.println(Thread.currentThread().getName()+"去唤醒别人...");
            LockSupport.unpark(t1);
        },"T2").start();

    }

    public static void main01(String[] args) {
        //用Condition实现线程通信
        new Thread(()->{
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName()+"Come in...,开始等待");
                condition.await();
                System.out.println(Thread.currentThread().getName()+"被唤醒...");
            }catch (Exception e){

            }finally {
                lock.unlock();
            }
        },"T1").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(()->{
            lock.lock();
            try {
                condition.signal();
                System.out.println(Thread.currentThread().getName()+"去唤醒别人...");
            }catch (Exception e){

            }finally {
                lock.unlock();
            }
        },"T2").start();
    }


}
